package com.ytjj.qmyx.mall.controller;

import com.ytjj.common.api.CommonResult;
import com.ytjj.qmyx.mall.model.RechargeRequest;
import com.ytjj.qmyx.mall.model.ReturnPhoneRechargeRequest;
import com.ytjj.qmyx.mall.model.request.RechargeCallbackRequest;
import com.ytjj.qmyx.mall.service.RechargeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 *  *
 **/
@RestController
@RequestMapping("/phoneRecharge")
@Slf4j
public class RechargeController {

    @Resource
    private RechargeService rechargeService;
    //手机充值开关  1-关闭 0-开启
    @Value("${phone.recharge.switch:1}")
    private Integer phoneRechargeSwitch;

    @PostMapping("/recharge")
    public CommonResult recharge(@Validated @RequestBody RechargeRequest rechargeRequest) {
        if (phoneRechargeSwitch.equals(1)) {
            return CommonResult.failed("充值维护中，请逛逛其它商品吧！");
        }
        rechargeService.recharge(rechargeRequest.getPhoneNo(), rechargeRequest.getOrderNo(),rechargeRequest.getRechargeAmount(),rechargeRequest.getOperators());
        return CommonResult.success();
    }

    /**
     * 手机充值-退款
     * 服务之间调用方法
     * @return
     */
    @PostMapping("/returnPhoneRecharge")
    public CommonResult returnPhoneRecharge(@Validated @RequestBody ReturnPhoneRechargeRequest request) {
        log.info("===手机充值退款==={}", request.toString());
        return CommonResult.success(rechargeService.rechargeFailByRpc(request.getType(), request.getOrderNo(), request.getRefundNo(), request.getAmount(), request.getDesc()));
    }

    @PostMapping("/callback")
    public void notify(@RequestBody RechargeCallbackRequest rechargeCallbackRequest, HttpServletResponse response) throws IOException {
        rechargeService.callback(rechargeCallbackRequest);
        response.getWriter().print("{\"respCode\":\"0000\"}");
    }

    @GetMapping("/testMq")
    public CommonResult testMq() {
        rechargeService.testMq();
        return CommonResult.success();
    }

    @GetMapping("/query/{orderNo}")
    public void query(@PathVariable("orderNo") String orderNo) {
        rechargeService.queryOrder(orderNo);
    }
}
